package com.javabasic.basic_learning;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * [说明]
 *
 * @author xiaoama
 * @date 2020/8/13 13:58.
 */
public class MyClassLoader extends ClassLoader {
    private String basePath;

    public MyClassLoader(String basePath) {
        this.basePath = basePath;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            byte[] bytes = loadClassData(name);
            return defineClass(name, bytes, 0, bytes.length);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ClassNotFoundException();
        }
    }

    @Override
    public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        Class<?> loadedClass = this.findLoadedClass(name);
        if (loadedClass != null) {
            return loadedClass;
        } else {
            try {
                Class<?> aClass = this.findClass(name);
                if (resolve) {
                    this.resolveClass(aClass);
                }
                return aClass;
            } catch (Exception var5) {
                return super.loadClass(name, resolve);
            }
        }
    }


    public byte[] loadClassData(String className) throws IOException {
        className = className.replaceAll("\\.", "/");
        String path = basePath + File.separator + className + ".class";
        FileInputStream fis = null;
        byte[] classBytes = new byte[0];
        fis = new FileInputStream(path);
        int length = fis.available();
        classBytes = new byte[length];
        fis.read(classBytes);
        fis.close();
        return classBytes;
    }

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        System.out.println(FileInputStream.class);
        HelloWorld helloWorld = new HelloWorld();
        System.out.println(helloWorld.getClass().hashCode());
        System.out.println(helloWorld.getClass().getClassLoader());
        System.out.println(helloWorld.getClass().getTypeName());
        System.out.println(helloWorld.getClass().getSimpleName());
        System.out.println(helloWorld.getClass());

        MyClassLoader myClassLoader = new MyClassLoader("/Users/mir/javaworks/javabasic/src/main/java/");
        Class<?> aClass = myClassLoader.loadClass("com.javabasic.basic_learning.HelloWorld");
        Object o = aClass.newInstance();
        System.out.println(o);
        System.out.println(o.getClass().getClassLoader());
    }
}


